// pages/test/test.js
const db = wx.cloud.database();
const fs = wx.getFileSystemManager();
const app = getApp();
const windowWidth = wx.getSystemInfoSync()["windowWidth"];
const httpUrl = "https://6d61-manbu-2ggvwdnk1d8bd0fa-1316354189.tcb.qcloud.la/";
var openid = "";
var today = new Date();
var nowday = new Date();
var calender = [[],[],[]];
var diaryArr = [];
var currentIndex = 1;
var rpxRate = wx.getSystemInfoSync()['screenWidth'] / 750;
var fixX = 0;
var fixY = 0;
var contextColor = {
    "愉悦": "rgba(250, 226, 192, 1);",
    "轻松": "rgba(253, 243, 192, 1);",
    "无语": "rgba(213, 236, 208, 1);",
    "发愁": "rgba(217, 217, 240, 1);",
    "崩溃": "rgba(188, 201, 207, 1);",
}
var contextEmoji = {
    "愉悦": "../../images/laughing.png",
    "轻松": "../../images/smile.png",
    "无语": "../../images/sighing.png",
    "发愁": "../../images/crying.png",
    "崩溃": "../../images/angry.png"
}
Page({

    /**
     * 页面的初始数据
     */
    data: {
        weekName: ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],
        swiperCurrent: 1,
        swiperDuration: 250,
        contextColor: contextColor,
        contextEmoji: contextEmoji,
        todayLeft: "310px",
        todayTop: "450px",
        isToday: true
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this;
        wx.cloud.callFunction({ //  调用云函数获取openid
            name: 'getopenid',
            complete: res => {
                openid = res.result.openid;
            }
        });
        this.init();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                selected: 3
            })
        }
    },
    init(){
        let date = new Date();
        date.setMonth(today.getMonth()-1);
        calender[0] = this.monthRefresh(date);
        calender[1] = this.monthRefresh(today);
        date.setMonth(today.getMonth()+1);
        calender[2] = this.monthRefresh(date);
        this.selectedRefresh(today);
        this.emojiRefresh(today);
        this.setData({
            calender: calender
        });
    },
    calenderRefresh(e){
        let index,source;
        if ( typeof e == "object" ) {
            index = e.detail.current;
            source = e.detail.source;
        }
        if ( typeof e == "number" ) {
            index = e;
            source = "function"
        }
        let date = new Date();
        date.setFullYear(nowday.getFullYear());
        date.setMonth(nowday.getMonth());
        date.setDate(nowday.getDate());
        if ( index == 0 ) {
            if ( currentIndex == 2 ) {
                nowday.setMonth(nowday.getMonth()+1);
                date.setMonth(date.getMonth()+2);
                calender[1] = this.monthRefresh(date);
            }
            if ( currentIndex == 1 ) {
                nowday.setMonth(nowday.getMonth()-1);
                date.setMonth(date.getMonth()-2);
                calender[2] = this.monthRefresh(date);
            }
            currentIndex = 0;
        }
        if ( index == 1 ) {
            if ( currentIndex == 0 ) {
                nowday.setMonth(nowday.getMonth()+1);
                date.setMonth(date.getMonth()+2);
                calender[2] = this.monthRefresh(date);
            }
            if ( currentIndex == 2 ) {
                nowday.setMonth(nowday.getMonth()-1);
                date.setMonth(date.getMonth()-2);
                calender[0] = this.monthRefresh(date);
            }
            currentIndex = 1;
        }
        if ( index == 2 ) {
            if ( currentIndex == 1 ) {
                nowday.setMonth(nowday.getMonth()+1);
                date.setMonth(date.getMonth()+2);
                calender[0] = this.monthRefresh(date);
            }
            if ( currentIndex == 0 ) {
                nowday.setMonth(nowday.getMonth()-1);
                date.setMonth(date.getMonth()-2);
                calender[1] = this.monthRefresh(date);
            }
            currentIndex = 2;
        }
        this.selectedRefresh(nowday);
        this.emojiRefresh(nowday);
        this.setData({
            calender: calender,
            year: nowday.getFullYear(),
            month: nowday.getMonth() + 1,
            day: nowday.getDate(),
            swiperCurrent: currentIndex
        });
    },
    monthRefresh(e){
        let date = new Date();
        let monthArr = [];
        let weekArr = [];
        if ( e != null ) {
            date.setFullYear(e.getFullYear());
            date.setMonth(e.getMonth());
            date.setDate(e.getDate());
        }  
        date.setDate(1);
        //给日历的第一行留位置
        if( date.getDay() != 0 ){
            //如果一号不是星期天，这个月从星期天那一天二十多号开始
            date.setDate( 1 - date.getDay() );
        } else {
            //如果是，第一行显示上个月的
            date.setDate(-6);
        }
        for( let i = 0; i < 6; i++ ) {
            for ( let j = 0; j < 7; j++ ) {
                let dateNum = String(date.getDate());
                let obj = {
                    isGrey : false,
                    dateNum : dateNum,
                    isSelected: false,
                    year: date.getFullYear(),
                    month: date.getMonth() + 1,
                    day: date.getDate(),
                    emoji: "",
                    image: "",
                    x: j,
                    y: i
                }
                if ( i == 0 && Number(dateNum) >= 10 )//上月末
                    obj["isGrey"] = true
                else if( i >= 4 && Number(dateNum) < 20 )//下月初
                    obj["isGrey"] = true;
                weekArr.push(obj);
                date.setDate(date.getDate() + 1);
            }
            monthArr.push(weekArr);
            weekArr = [];
        }
        return monthArr;
    },
    dateTap(e){
        let year = e.currentTarget.dataset.year;
        let month = e.currentTarget.dataset.month;
        let day = e.currentTarget.dataset.day;
        let lastYM = 100 * nowday.getFullYear() + nowday.getMonth() + 1;
        let date = new Date();
        date.setFullYear(Number(year));
        date.setMonth(Number(month)-1);
        date.setDate(Number(day));
        app.globalData.date = date;
        let nowdayYM = 100 * date.getFullYear() + date.getMonth() + 1;
        //console.log(date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日");
        if ( lastYM < nowdayYM ) {
           //this.wrapToNowday(date);
        }
        else if ( lastYM == nowdayYM ) {
            
            nowday.setFullYear(date.getFullYear());
            nowday.setMonth(date.getMonth());
            nowday.setDate(date.getDate());
            this.selectedRefresh(nowday);
        }
        else if ( lastYM > nowdayYM ) {
            //this.wrapToNowday(date)
        }
    },
    selectionMove(x,y){
        let animation = wx.createAnimation({
            duration: 500,
            timingFunction: 'ease',
        });
        let fix = 0;
        if ( rpxRate < 0.52 )
            fix = 1+y/5;
        if ( rpxRate > 0.52 )
            fix = -(1+y/5);
        animation.translate(x*(750/7)*rpxRate, Math.floor((y*120+y)*rpxRate)+fix).step()
        this.setData({
            ani:  animation.export()
        })
    },
    selectedRefresh(e){
        let date = new Date();
        let x = 0;
        let y = 0;
        if ( e != null ){
            date.setFullYear(e.getFullYear());
            date.setMonth(e.getMonth());
            date.setDate(e.getDate());
        }
        for( let i = 0; i < 6; i++ ) {
            for ( let j = 0; j < 7; j++ ) {
                let obj = calender[currentIndex][i][j];
                obj["isSelected"] = false;
                if( obj["year"] == date.getFullYear() && obj["month"] == date.getMonth() + 1 && obj["day"] == date.getDate() ) {
                    obj["isSelected"] = true;
                    x = obj["x"];
                    y = obj["y"];
                }
            }
        }
        this.diaryRefresh(date);
        this.selectionMove(x,y);
        let isToday = true;
        if ( date.getFullYear() != today.getFullYear() || date.getMonth() != today.getMonth() || date.getDate() != today.getDate() )
            isToday = false;
        this.setData({
            calender: calender,
            year: date.getFullYear(),
            month: date.getMonth() + 1,
            day: date.getDate(),
            currentPage: currentIndex,
            isToday: isToday
        });
    },
    emojiRefresh(e){
        let that = this;
        let date = new Date();
        if ( e != null ){
            date.setFullYear(e.getFullYear());
            date.setMonth(e.getMonth());
            date.setDate(e.getDate());
        }
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        if ( !openid ) {
            openid = app.globalData.openid
        }
        let emojiDict = {
            "愉悦": "../../images/laughing.png",
            "轻松": "../../images/smile.png",
            "无语": "../../images/sighing.png",
            "发愁": "../../images/crying.png",
            "崩溃": "../../images/angry.png"
        }
        if ( openid ) {
            db.collection("diaryDB").where({
                _openid: openid,
                year: year,
                month: month
            }).get({
                success: function(res){
                    let data = res.data;
                    for ( let h = 0; h <= 2; h++ ) {
                        for ( let i = 0; i < 6; i++ ){
                            for ( let j = 0; j < 7; j++ ){
                                calender[h][i][j]["emoji"] = "";
                                for ( let k in data ) {
                                    if ( calender[h][i][j]["day"] == data[k]["day"] && calender[h][i][j]["month"] == data[k]["month"] && calender[h][i][j]["month"] == month ) {
                                        calender[currentIndex][i][j]["emoji"] = emojiDict[data[k]["emoji"]];
                                    }
                                }
                            }
                        }
                    }
                    that.setData({
                        calender: calender
                    });
                }
            });
        }
        else {
            wx.showLoading({
              title: '加载中...',
            })
            setTimeout(function(){
                that.emojiRefresh();
                that.diaryRefresh(today);
                wx.hideLoading();
            },1000)
        }
    },
    diaryRefresh(e){
        let that = this;
        let date = new Date();
        if ( e != null ){
            date.setFullYear(e.getFullYear());
            date.setMonth(e.getMonth());
            date.setDate(e.getDate());
        }
        db.collection("diaryDB").where({
            _openid: openid,
            year: date.getFullYear(),
            month: date.getMonth() + 1,
            day: date.getDate()
        }).get({
            success: function(res){
                diaryArr = res.data;
                for ( let i in diaryArr ) {
                    diaryArr[i]["timeString"] = diaryArr[i]["createTime"].valueOf();
                    if ( diaryArr[i]["cloudPath"] != {} ) {
                        //that.loadImage(diaryArr[i]);
                        let images = [];
                        for ( let j in diaryArr[i]["cloudPath"] ) {
                            let url = diaryArr[i]["cloudPath"][j];
                            let image = httpUrl + url.substr(72,url.length);
                            images.push(image);
                        }
                        diaryArr[i]["images"] = images;
                        diaryArr[i]["timeString"] = diaryArr[i].createTime.valueOf();
                        db.collection("infoDB").where({
                            _openid: diaryArr[i]["_openid"]
                        }).get({
                            success: function(res){
                                if ( res.data.length == 0 ) {
                                    diaryArr[i]["nickname"] = "微信用户";
                                    diaryArr[i]["avatar"] = defaultAvatarUrl;
                                }
                                else {
                                    diaryArr[i]["nickname"] = res.data[0].nickname;
                                    if ( res.data[0].avatar )
                                        diaryArr[i]["avatar"] = that.loadAvatar(res.data[0].avatar);
                                    else
                                        diaryArr[i]["avatar"] = defaultAvatarUrl;
                                }
                                that.setData({
                                    diaryArr: diaryArr
                                });
                            }
                        })

                        diaryArr[i]["likeNumber"] = Object.keys(diaryArr[i]["like"]).length;
                        diaryArr[i]["favouriteNumber"] = Object.keys(diaryArr[i]["favourite"]).length;

                        let maxLikeIndex = 0;
                        for ( let j in diaryArr[i]["comment"] ) {
                            let likeNumber = Object.keys(diaryArr[i]["comment"][j]["like"]).length;
                            if ( likeNumber >= Object.keys(diaryArr[i]["comment"][maxLikeIndex]["like"]).length )
                                maxLikeIndex = j;
                        }
                        if ( diaryArr[i]["comment"].length > 0 ) {
                            db.collection("infoDB").where({
                                _openid: diaryArr[i]["comment"][maxLikeIndex]["openid"]
                            }).get({
                                success: function(res){
                                    if ( res.data.length == 0 ) {
                                        diaryArr[i]["hotCommentNickname"] = "微信用户";
                                        diaryArr[i]["hotCommentAvatar"] = defaultAvatarUrl;
                                        diaryArr[i]["comment"][maxLikeIndex]["comment"];
                                    }
                                    else {
                                        diaryArr[i]["hotCommentNickname"] = res.data[0].nickname;
                                        if ( res.data[0].avatar )
                                            diaryArr[i]["hotCommentAvatar"] = that.loadAvatar(res.data[0].avatar);
                                        else
                                            diaryArr[i]["hotCommentAvatar"] = defaultAvatarUrl;
                                        diaryArr[i]["hotComment"] = diaryArr[i]["comment"][maxLikeIndex]["comment"];
                                    }
                                    that.setData({
                                        diaryArr: diaryArr
                                    });
                                }
                            });
                        }
                    }
                }
                that.setData({
                    diaryArr: diaryArr
                });
            }
        });
    },
    loadAvatar(url){
        let file = url.substr(70,url.length);
        return httpUrl + file;
    },
    loadImage(e){
        let that = this;
        let data = e;
        let promises = [];
        for ( let i in data["localPath"] ) {
            let p = new Promise(function(resolve,reject){
                fs.access({
                    path: data["localPath"][i],
                    success(res) {
                        resolve(data["localPath"][i]);
                    },
                    fail(res) {
                        reject(data["cloudPath"]);
                    }
                });
            });
            promises.push(p);
        }
        let p2 = Promise.all(promises).then((res)=>{
        }).catch((res)=>{
            wx.showLoading({
                title: '加载图片中',
            });
            that.downloadImage(res,data._id);
        });
    },
    downloadImage(e,id){
        let that = this;
        let data = e;
        let imageNeedDownload = [];
        for ( let i in data ) {
            if(i.substring(i.length-5,i.length).includes(".")){
                let p = new Promise(function(resolve,reject){
                    wx.cloud.downloadFile({
                        fileID: data[i],
                        success(res){
                            resolve(res.tempFilePath)
                        },
                        fail(res){
                            reject(res);
                        }
                    });
                });
                imageNeedDownload.push(p);
            }
        }
        let p2 = Promise.all(imageNeedDownload).then((res)=>{
            wx.showToast({
                title: '加载成功！',
                icon: "success",
                duration: 500
            });
            db.collection("diaryDB").where({
                _id: id,
            }).update({
                data: {
                    localPath: res
                },
                success: function(res){
                    that.diaryRefresh(nowday);
                }
            });
        }).catch((res)=>{
            wx.showToast({
                title: '加载失败！',
                icon: "error",
                duration: 2000
            });
        })
    },
    fixDiary(e){
        let id = e.currentTarget.dataset.id;
        let emoji = e.currentTarget.dataset.emoji;
        let diary = e.currentTarget.dataset.diary;
        let images = e.currentTarget.dataset.images;
        let publish = e.currentTarget.dataset.publish;
        let cloudPath = e.currentTarget.dataset.cloudimage;
        let timeString = e.currentTarget.dataset.timestring;
        wx.navigateTo({
            url: '../diary/diary',
            success: function(res) {
                res.eventChannel.emit('acceptDataFromOpenerPage',{year:nowday.getFullYear(),month:nowday.getMonth()+1,authorid:openid,day:nowday.getDate(),emoji:emoji,diary:diary,id:id,cloudimage:cloudPath,images:images,publish:publish,fixmode: false,visit:false,timeString:timeString});
            }
        })
    },
    displayLastMonth(e){
        if ( currentIndex == 0 )
            this.calenderRefresh(2);
        else if ( currentIndex == 1 )
            this.calenderRefresh(0);
        else if ( currentIndex == 2 )
            this.calenderRefresh(1);
    },
    displayNextMonth(e){
        if ( currentIndex == 0 )
            this.calenderRefresh(1);
        else if ( currentIndex == 1 )
            this.calenderRefresh(2);
        else if ( currentIndex == 2 )
            this.calenderRefresh(0);
    },
    dateChange(e){
        let value = e.detail["value"];
        let year = value.substring(0,4);
        let month = value.substring(5,7);
        let day = value.substring(8,10);
        let date = new Date();
        date.setFullYear(Number(year));
        date.setMonth(Number(month)-1);
        date.setDate(Number(day));
        this.wrapToNowday(date);
    },
    wrapToNowday(e){
        let date = new Date();
        if ( e != null ) {
            date.setFullYear(e.getFullYear());
            date.setMonth(e.getMonth());
            date.setDate(e.getDate());
        }
        let nowdayYM = 100 * nowday.getFullYear() + nowday.getMonth() + 1;
        let dateYM = 100 * date.getFullYear() + date.getMonth() + 1;
        if ( nowdayYM < dateYM ) {
            if ( currentIndex == 0 ) {
                nowday.setFullYear(date.getFullYear());
                nowday.setMonth(date.getMonth());
                nowday.setDate(date.getDate());
                nowdayYM = 100 * nowday.getFullYear() + nowday.getMonth() + 1;
                if ( nowdayYM != dateYM ) { //不明bug的修正
                    nowday.setFullYear(date.getFullYear());
                    nowday.setMonth(date.getMonth());
                    nowday.setDate(date.getDate());
                }
                date.setMonth(nowday.getMonth()-1);
                calender[0] = this.monthRefresh(date);
                calender[1] = this.monthRefresh(nowday);
                date.setMonth(nowday.getMonth()+1);
                calender[2] = this.monthRefresh(date);
                currentIndex = 1;
            }
            else if ( currentIndex == 1 ) {
                nowday.setFullYear(date.getFullYear());
                nowday.setMonth(date.getMonth());
                nowday.setDate(date.getDate());
                date.setMonth(nowday.getMonth()-1);
                calender[1] = this.monthRefresh(date);
                calender[2] = this.monthRefresh(nowday);
                date.setMonth(nowday.getMonth()+1);
                calender[0] = this.monthRefresh(date);
                currentIndex = 2;
            }
            else if ( currentIndex == 2 ) {
                nowday.setFullYear(date.getFullYear());
                nowday.setMonth(date.getMonth());
                nowday.setDate(date.getDate());
                date.setMonth(nowday.getMonth()-1);
                calender[2] = this.monthRefresh(date);
                calender[0] = this.monthRefresh(nowday);
                date.setMonth(nowday.getMonth()+1);
                calender[1] = this.monthRefresh(date);
                currentIndex = 0;
            }
        }
        else if ( nowdayYM > dateYM ) {
            if ( currentIndex == 0 ) {
                nowday.setFullYear(date.getFullYear());
                nowday.setMonth(date.getMonth());
                nowday.setDate(date.getDate());
                date.setMonth(nowday.getMonth()-1);
                calender[1] = this.monthRefresh(date);
                calender[2] = this.monthRefresh(nowday);
                date.setMonth(nowday.getMonth()+1);
                calender[0] = this.monthRefresh(date);
                currentIndex = 2;
            }
            else if ( currentIndex == 1 ) {
                nowday.setFullYear(date.getFullYear());
                nowday.setMonth(date.getMonth());
                nowday.setDate(date.getDate());
                date.setMonth(nowday.getMonth()-1);
                calender[2] = this.monthRefresh(date);
                calender[0] = this.monthRefresh(nowday);
                date.setMonth(nowday.getMonth()+1);
                calender[1] = this.monthRefresh(date);
                currentIndex = 0;
            }
            else if ( currentIndex == 2 ) {
                nowday.setFullYear(date.getFullYear());
                nowday.setMonth(date.getMonth());
                nowday.setDate(date.getDate());
                date.setMonth(nowday.getMonth()-1);
                calender[0] = this.monthRefresh(date);
                calender[1] = this.monthRefresh(nowday);
                date.setMonth(nowday.getMonth()+1);
                calender[2] = this.monthRefresh(date);
                currentIndex = 1;
            }
        }
        else if ( nowdayYM == dateYM ) {
            nowday.setFullYear(date.getFullYear());
            nowday.setMonth(date.getMonth());
            nowday.setDate(date.getDate());
            this.selectedRefresh(nowday);
        }
        this.setData({
            year: nowday.getFullYear(),
            month: nowday.getMonth() + 1,
            day: nowday.getDate(),
            swiperCurrent: currentIndex
        });
    },
    backToToday(e){
        this.wrapToNowday(today);
        this.setData({
            isToday: true
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let that = this;
        this.wrapToNowday(nowday)
        this.emojiRefresh(nowday);
        this.diaryRefresh(nowday);
        this.setData({
            calender: calender,
            diaryArr: diaryArr
        });
        setTimeout(function(){
            that.emojiRefresh(nowday);
            that.diaryRefresh(nowday);
            that.setData({
                calender: calender
            });
        },300);
        
    },
    todayTouchStart(e){
        this.setData({
            startX: e.changedTouches[0].clientX,
            startMove: false
        })
    },
    todayTouchMoving(e){
        if ( this.data.startMove == false ) {
            let todayLeft = Number(this.data.todayLeft.substring(0,this.data.todayLeft.length-2));
            let todayTop = Number(this.data.todayTop.substring(0,this.data.todayTop.length-2));
            fixX = e.changedTouches[0].clientX - todayLeft;
            fixY = e.changedTouches[0].clientY - todayTop;
            this.setData({
                startX: e.changedTouches[0].clientX,
                startY: e.changedTouches[0].clientY,
                startMove: true
            })
        }
        this.setData({
            todayLeft: (e.changedTouches[0].clientX - fixX) + "px",
            todayTop: (e.changedTouches[0].clientY - fixY) + "px",
        })
    },
    todayTouchEnd(e){
        let that = this;
        let endX = e.changedTouches[0].clientX;
        let endY = e.changedTouches[0].clientY;
        let todayLeft = Number(this.data.todayLeft.substring(0,this.data.todayLeft.length-2));
        // 左
        if ( endX < windowWidth / 2 ) {
            let animation = wx.createAnimation({
                duration: 1000,
                timingFunction: 'ease',
            });
            animation.translateX(5-todayLeft).step()
            this.setData({
                todayAni:  animation.export()
            })
            setTimeout(function(){
                animation = wx.createAnimation({
                    duration: 0
                });
                animation.translateX(0).step()
                that.setData({
                    todayAni:  animation.export(),
                    todayLeft: "5px"
                })

            },1000);
        }
        // 右
        else {
            let animation = wx.createAnimation({
                duration: 1000,
                timingFunction: 'ease',
            });
            animation.translateX(windowWidth-todayLeft-60).step()
            this.setData({
                todayAni:  animation.export()
            })
            setTimeout(function(){
                animation = wx.createAnimation({
                    duration: 0
                });
                animation.translateX(0).step()
                that.setData({
                    todayAni:  animation.export(),
                    todayLeft: (windowWidth - 60) +"px"
                })
            },1000);
        }
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})